<?php
namespace app\shouyin\admin;
use app\system\admin\Admin;
use app\finance\model\Classofreim as ClassofreimModel;
use app\shop\model\Shop as ShopModel;
use app\system\model\systemUser as systemUserModel;
use app\shouyin\model\Reim as ReimModel;
use app\finance\model\Account as AccountModel;
use app\user\model\User as UserModel;
use think\Db;
class Reim extends Admin
{
    protected $hisiModel = 'Reim';//模型名称[通用添加、修改专用]
    protected $hisiTable = '';//表名称[通用添加、修改专用]
    protected $hisiAddScene = '';//添加数据验证场景名
    protected $hisiEditScene = '';//更新数据验证场景名
    protected function initialize()
    {
        parent::initialize();
        if ($this->request->action() != 'index' && !$this->request->isPost()) {
            $category = ClassofreimModel::getSelect(ClassofreimModel::getChilds());
            $this->assign('category', $category);
            $shops = ShopModel::getSelect(ShopModel::all());
            $this->assign('shops', $shops);
            $admins = systemUserModel::getSelect(systemUserModel::all());
            $this->assign('admins', $admins);
            $accounts = AccountModel::getSelect(AccountModel::all());
            $this->assign('accounts', $accounts);

        }
    }
    public function index()
    {

        if ($this->request->isAjax()) {
            $where      = [];
            $page       = $this->request->param('page/d', 1);
            $limit      = $this->request->param('limit/d', 15);
            $type      = $this->request->param('type', 1);
            $admin_id      = $this->request->param('admin_id', '');
            $shop_id      = $this->request->param('shop_id', '');
            $class_id      = $this->request->param('class_id', '');
            $title      = $this->request->param('title', '');
            $start      = $this->request->param('start', '2000-01-01');
            $end      = $this->request->param('end','');
            if(!empty($admin_id)){
                $where[] = ['admin_id','=',$admin_id];
            }
            if(!empty($shop_id)){
                $where[] = ['shop_id','=',$shop_id];
            }
            if(!empty($class_id)){
                $where[] = ['class_id','=',$class_id];
            }
            if(!empty($title)){
                $where[] = ['title','like','%'.$title.'%'];
            }
            if(empty($start)){
                $start = '2000-01-01';
            }
            if(empty($end)){
                $end = date('Y-m-d',strtotime("+1 day"));
            }
            if($type == 2){
                $data['data'] = ReimModel::where($where)
                                ->field('*,class_id as class_name, shop_id as shop_name,admin_id as admin_name, finance_id as finance_name,account_id as account_name')
                                ->where('createtime','between',[strtotime($start),strtotime($end)])
                                ->order('id desc')
                                ->select();
                foreach ($data['data'] as $key => $value) {
                    if($value['status'] == 1){
                        $data['data'][$key]['status_text'] = '待审核';
                    }else if($value['status'] == 2){
                        $data['data'][$key]['status_text'] = '审核通过';
                    }else{
                        $data['data'][$key]['status_text'] = '审核不通过';
                    }
                }
                $data['count'] = ReimModel::where($where)->where('createtime','between',[strtotime($start),strtotime($end)])->count('id');
                $data['code'] = 0;
                return json($data);
            }else{
                $data['data'] = ReimModel::where($where)
                                ->field('*,class_id as class_name, shop_id as shop_name,admin_id as admin_name, finance_id as finance_name,account_id as account_name')
                                ->where('createtime','between',[strtotime($start),strtotime($end)])
                                ->page($page)
                                ->limit($limit)
                                ->order('id desc')
                                ->select();
                // echo ReimModel::getlastsql();
                $data['count'] = ReimModel::where($where)->where('createtime','between',[strtotime($start),strtotime($end)])->count('id');
                $data['code'] = 0;
                return json($data);
            }

        }
        $users = systemUserModel::field('id,nick')->all();
        $this->assign('users', $users);
        $shops = ShopModel::field('id,name')->all();
        $this->assign('shops', $shops);
        $category = ClassofreimModel::getSelect(ClassofreimModel::getChilds());
        $this->assign('category', $category);
        return $this->fetch();
    }

    public function edit()
    {
        if ($this->request->isPost()) {// 数据验证
            $postData = $this->request->post();
        }
        $where = [];
        $db = Db::name('reim');
        $pk = $db->getPk();
        $id = $this->request->param($pk);
        
        $where[]= [$pk, '=', $id];
        $where  = $this->getRightWhere($where);
        Db::startTrans();
        if ($this->request->isPost()) {
            $postData['usetime'] = strtotime($postData['usetime']);

            try {
                if (!$db->where($where)->update($postData)) {
                    throw new \Exception("保存失败");
                }

                if($postData['status'] == 2){
                    if($postData['account_id'] == 0){
                        throw new \Exception("请选择正确的支出账户");
                    }
                    $ins = [
                        'sn' => $postData['sn'],
                        'type' => 4,
                        'account_id' => $postData['account_id'],
                        'shop_id' => $postData['shop_id'],
                        'price' => $postData['price'],
                        'createtime' => time(),
                        'updatetime' => time(),
                        'is_effective' => 1,
                        'cate' => 2,
                    ];
                    Db::name('system_balance_log')->insert($ins);
                }
                // 提交事务
                Db::commit();
                // throw new \Exception("用户余额不足！");
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return $this->error($e->getMessage(), false);
            }
            return $this->success('审核完成');
        }

        $formData = $db->where($where)->find();
        $type = $this->request->param('type');
        $this->assign('type',$type);

        if (!$formData) {
            return $this->error('数据不存在或没有权限');
        }

        $this->assign('formData', $formData);
        $this->assign('admin_id', ADMIN_ID);
        // halt(ADMIN_ID);
        $template = $this->request->param('template', 'form');
        if(!is_empty($this->request->param('xx')) && $this->request->param('xx') == 2){
            $formData['shop_name'] = Db::name('shop')->where('id',$formData['shop_id'])->value('name');
            $formData['classofreim'] = Db::name('classofreim')->where('id',$formData['class_id'])->value('name');
            $formData['admin_name'] = Db::name('system_user')->where('id',$formData['admin_id'])->value('nick');
            $formData['account_name'] = Db::name('account')->where('id',$formData['account_id'])->value('name');
            $this->view->engine->layout(false);
            $this->assign('formData', $formData);
            return $this->fetch('dayin');
        }
        return $this->fetch($template);
    }

}
